package com.shunli.cterminal.util;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author huanghongyi
 * @date 2023/12/29 12:34 AM
 */
@Slf4j
public class QmLibraUtils {

    public static List<String> getTargetBucketIds(String bucketIdsUsed, Integer targetCnt) {
        Set<Integer> ids = new HashSet<>();

        if (StringUtils.isNotEmpty(bucketIdsUsed)) {
            String[] idArray = bucketIdsUsed.split(",");
            for (String t : idArray) {
                ids.add(Integer.valueOf(t));
            }
        }
        if (targetCnt > 100 - ids.size()) {
            return null;
        }

        List<String> avaIds = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            if (ids.contains(i)) {
                continue;
            }
            avaIds.add(String.valueOf(i));
            if (avaIds.size() >= targetCnt) {
                break;
            }
        }
        return avaIds;
    }

    public static List<String> merge2BucketIds(String bucketIdsUsed, List<String> bucketIds) {

        Set<String> ids = new HashSet<>();
        if (StringUtils.isNotEmpty(bucketIdsUsed)) {
            String[] idArray = bucketIdsUsed.split(",");
            for (String t : idArray) {
                ids.add(t);
            }
        }
        if(CollectionUtil.isNotEmpty(bucketIds)){
            ids.addAll(bucketIds);
        }

        List<String> result = new ArrayList<>(ids);
        return result;
    }

    public static List<String> remove2BucketIds(String bucketIdsUsed, List<String> bucketIds) {

        Set<String> ids = new HashSet<>();
        if (StringUtils.isNotEmpty(bucketIdsUsed)) {
            String[] idArray = bucketIdsUsed.split(",");
            for (String t : idArray) {
                ids.add(t);
            }
        }
        if(CollectionUtil.isNotEmpty(bucketIds)){
            for(String item: bucketIds){
                ids.remove(item);
            }
        }

        List<String> result = new ArrayList<>(ids);
        return result;
    }

    /**
     * hash 取模
     * @param str
     * @param modValue
     * @return
     */
    public static Long murmurHashSplit(String str, Integer modValue){
        HashFunction hashFunction = Hashing.murmur3_128();
        //String v= hashFunction.hashString(str, StandardCharsets.UTF_8).toString();

        if(modValue==null){
            modValue=100;
        }
        Long bucketId =Math.abs(hashFunction.hashUnencodedChars(str).asLong()) % modValue +1;
        return bucketId;
    }


}
